<?php

class ProductController extends BaseController
{
    public function init()
    {
        $this->req = $this->getRequest();
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        $article_id = $this->req->get('article_id');
        if ($article_id == false) {exit('文章id 不能为空');}
        // 验证授权信息
        $uid = $this->user_id;
        // 预生成文章
        $article = new \Base\Rest();
        $req = array('uid'=>$uid);
        $post = array('article_id'=>$article_id);

        $post = array(
            'payload' => base64_encode(http_build_query($post))
        );

        $rest_res = $article->post('Product',$req,$post);
        if ($rest_res->isSuccess() == true) {
            $res = $rest_res->getResponse();
            $this->_redirect('/product/edit?id='.$res->id);
        } else {
            exit('服务器内部错误');
        }
    }

    public function editAction()
    {
        $this->view->title="编辑";
        $id = $this->req->get('id');
        if ($id == false) {exit('商品 id 不能为空');}
        $rest = new \Base\Rest();
        $req = array('uid'=>$this->user_id);
        $res = $rest->get('Product',$id,$req);
        if ($res->isSuccess() == false ) {exit('未找到商品');}
        $this->view->info = $res->getResponse();
        $this->view->oss_url_path = \Util\Config::get('url_path','Oss');
        $this->view->oss_dir = \Util\Config::get('dir','Oss');
        $this->view->allowed_image_type = count(\Util\Config::get('allowed_image_type','Oss')) ? \Util\Config::get('allowed_image_type','Oss') : array();
        $this->view->allowed_image_size = \Util\Config::get('allowed_image_size','Oss');
    }

    public function updateAction()
    {
        if ($this->req->isPost() == false ) {Response::Error(500,'非法请求');}
        $id = $this->req->getPost('id');
        if ($id == false ) {Response::Error(500,'id不能为空');}
        $name = $this->req->getPost('name');
        if ($name == false ) {Response::Error(500,'商品名称不能为空');}
        $unit_price = $this->req->getPost('unit_price');
        if ($unit_price == false ) {Response::Error(500,'商品单价不能为空');}
        $describe = $this->req->getPost('describe');
        $image_id_list = $this->req->getPost('image_id_list');
        $req = array(
            'uid'=>$this->user_id
        );
        $data = array(
            'name' => $name,
            'unit_price' => $unit_price,
            'sort' => 1, // todo sort
            'status' => \Orm\Product\ProductClass::STATUS_VALID,
            'describe' => $describe,
            'image_id_list' => json_encode($image_id_list),
        );
        $post = array(
            'payload' => base64_encode(http_build_query($data))
        );
        $rest = new \Base\Rest();
        $res = $rest->put('Product',$id,$req,$post);

        if ($res->isSuccess()) {
            Response::Success($res->getResponse());
        } else {
            Response::Error(500,$res->getErrorMessage());
        }
    }
}



